// @Author EthanScriptOn
// @Desc
package util

import (
	"errors"
	"regexp"
	"runtime"
	"strings"
)

// StackPrint Stack printing
func StackPrint() string {
	bytes := make([]byte, 10240)
	sizeLen := 0
	for {
		size := runtime.Stack(bytes, false)
		sizeLen += size
		if size == len(bytes) {
			bytes = make([]byte, len(bytes)<<1)
			continue
		}
		break
	}
	return string(bytes[:sizeLen])
}

// GetGoroutineId Obtain the coroutine ID
func GetGoroutineId(trace string) (string, error) {
	traceSlice := strings.Split(trace, "\n")
	if len(traceSlice) <= 0 {
		return "", errors.New("trace is empty")
	}
	re := regexp.MustCompile(`\d+`)
	matches := re.FindStringSubmatch(traceSlice[0])
	if len(matches) <= 0 {
		return "", errors.New("unable to obtain goroutine ID")
	}
	return matches[0], nil
}
